<?php

namespace app\common\model;

use think\Exception;

class CmsDatabaseBackup extends BaseModel {
    public $config;
    public $backup;

    public function __construct($data = []) {
        parent::__construct($data);
        //获取系统数据库配置信息
        $this->config = \think\Config::get("database");
        //创建备份对象
        $this->backup = new \org\Baksql($this->config);
    }

    //添加备份
    public function addBackups($bak_description) {
        $info = $this->backup->backup();
        if ($info['status'] === "success") {
            //当储存成功时，根据信息往数据库中插入数据
            //取出管理员信息
            $bak_admin_id = session("adminInfo")['adm_id'];
            $info['bak_size']=str_replace("KB","",$info['bak_size']);
            $data = [
                "bak_name" => $info['bak_name'],
                "bak_description" => $bak_description,
                "bak_size" => $info['bak_size'],
                "bak_create_time" => time(),
                "bak_admin_id" => $bak_admin_id
            ];
            try {
                $this->insert($data);
            } catch (Exception $exception) {
                return [
                    "status" => "fail",
                    "msg" => "数据库插入异常"
                ];
            }
        }
        //直接把$info返回回去
        return $info;
    }


    public function deleteBackups($data) {
        //删除备份的sql文件
        $this->backup->delfilename($data['bak_name']);

        //删除数据库中的数据
        try {
            $this->where("bak_id", "=", $data['bak_id'])->delete();
        }catch (Exception $exception){
            return "数据删除异常";
        }
        return 1;
    }

    public function test() {
        //获取操作内容：（备份/下载/还原/删除）数据库
        $type = "query";
        //获取需要操作的数据库sql文件的名称
        $name = "2019cms";
        $backup = new \org\Baksql(\think\Config::get("database"));
        switch ($type) {
            //备份
            case "backup":
                $info = $backup->backup();
                $this->success("$info");
                break;
            //下载
            case "dowonload":
                $info = $backup->downloadFile($name);
                $this->success("$info");
                break;
            //还原
            case "restore":
                $info = $backup->restore($name);
                $this->success("$info");
                break;
            //删除
            case "del":
                $info = $backup->delfilename($name);
                $this->success("$info");
                break;

            case "query":
                $list = array_reverse($backup->get_filelist());
                return json($list);
            //如果没有操作，则查询已备份的所有数据库信息
            default:
                return $this->fetch("index", ["list" => array_reverse($backup->get_filelist())]);//将信息由新到老排序
        }
    }
}
